import socket
import cPickle as pickle
def connecter():
	sock = socket.socket()
	sock.connect((socket.gethostname(),12345))
	return sock
def loaddata(data):
	definitions = {}
#the definition dictionary
	FILE = open(data,'r')
#open the definition file
	started = False
	read = False
#checker to know if this is the first headdig
	heading=""
	fields=[]	
#initialize the values for the first definition
	for f in FILE:
		f=f.strip() 
		#print "<",f,">"
		if not f:
			continue
		elif f[0]=="#":
			continue
		if f[:5] == 'head:':
		
			if started:#this will only be true if the values for the definition are populated with at least a heading
				definitions[heading]=sentence(heading,fields) #add the definition to the dictionary using its heading as the key
				heading=""
				fields=[]
            #reinitalize the fields
			started = True#there is at least a heading to be added to the dictionary
			heading=f[5:]#set the heading
      			read = True
		elif f[:6] =='field:':
			fields.append(f[6:])#add the field to the fields
		#elif f[:3] =="end:":
		#	if started:#this will only be true if the values for the definition are populated with at least a heading
		#		definitions[heading]=sentence(heading,fields) #add the definition to the dictionary using its heading as the key
		#		heading=""
		#		fields=[]
    		else:
      			continue#not a valid tag, ignore it
  	if read:
  		definitions[heading]=sentence(heading,fields)#add the final heading to the dictionary but only if the sucker has read something so we dont get a null entry
	return definitions




def makedata(line,definitions,data):
	line = line[1:]#ditch the leading $
	head = line[:5]#get the sentence heading
	fieldstr = line[6:-3]#the unparsed csv of the sentence	
	#todo SPLIT THE FIELDS AND COMPARE THEM TO THE DEFINITION
	#print fields
	#print fields.split(',')
	
	fields=fieldstr.split(",")
	zipped = zip(definitions[head].getfields(), fields)	
	for (value, field) in zipped:
		data[head][value]=field
	#print "###############################"
	sock = connecter()
	sock.send("spite")
	sockFILE = sock.makefile()	
	pickle.dump(data,sockFILE)
	sockFILE.close()
	


	

	

def checksum(line):
	line= line.strip('$')#strip the $ cause it doesnt get summed
	#print "stripped:",line	
	
	sum = 0#set the checksum at 0 to start
	for itrchar in line:#we iterate through each char cause the checksum is a bitwise ore
		if itrchar == line[-3]:#we want to stop at the * cause thats the sum and doesnt get included
			break	
		sum = sum ^  ord(itrchar)#bitwise or for the checksum
	checkstring = hex(sum)[-2:].upper()#get the string we've created, ditch the 0x and make it uppercase
	stringtocheck = line[-2:]#get the string we want to check
	#print stringtocheck, " vs ", checkstring
	if stringtocheck == checkstring:return True#check they match and if they do we're all good
	else : return False#the fuckers didnt match
def check(line):
	if not line.startswith('$'):return False#check it starts with $ to make sure its a full sentence
	elif not checksum(line): return False#do the checksum
	else:return True	

def getstream(path,definitionpath):
	data = {}
	
	definitions = loaddata(definitionpath)
	print definitions.keys()
	for deff in definitions.keys():
		data[deff]={}
	FILE = open(path,'r')#openfile
	while True:
		line = ""#initalize the line
		line = getline(path,line,FILE)
		line = line.strip()#strip the \n the line comes with
		if not check(line): continue#print "Garbage"#check the line
		else: makedata(line,definitions,data)#make the data
	
		
		 
def getline(path, line,FILE):
	line = FILE.readline()
	print "{0}".format(line.strip())
	return line
	
		
class sentence:
	headding=""
	fields=[]
	def __init__(self,headding="",fields=[]):
		self.headding=headding
		self.fields=fields
		return
	def setheadding(self,headding):
		self.headding=headding	
		return
	def getfields(self):
		return self.fields
	def setfields(self,fields):
		for field in fields:
			self.fields.append(field) 
		return
	def getheadding(self):
		return self.headding
	def addfield(self,field):
		self.fields.append(field)
		return
	def setfield(self,fieldvaluse,fieldindex):
		self.fields[fieldindex]=fieldvalue
	def getfield(self,field):
		return self.fields[field]
	def getnumberfields(self):
		len(self.fields)
		
getstream('/dev/ttyUSB0','./definitions')	
